package com.escom.dao;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.escom.entidad.MedicoVO;
import com.escom.entidad.UsuarioVO;
import com.escom.utils.Constantes;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Carlos on 7/04/14.
 */
public class MedicoDAO {

    private Context context;
    private Handler handler;
    private SharedPreferences sharedpreferences;

    public MedicoDAO(Context context) {
        this.context = context;
    }

    public void createMedico(MedicoVO medico) {
        DataBaseManager dataBaseManager = new DataBaseManager(this.context);
        SQLiteDatabase sqLiteDatabase = dataBaseManager.getWritableDatabase();
        Log.d(Constantes.LOG_ID, this.getClass().getName() + " medicoString: " +medico.toString());
        if (sqLiteDatabase != null) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constantes.FORMAT_DATE);
            String ultimaConexion = simpleDateFormat.format(calendar.getTime());
            Date lastUpdate = medico.getUsuario().getUltimaActualizacionDate();
            String lastUpdateString = simpleDateFormat.format(lastUpdate);
            Log.d(Constantes.LOG_ID, this.getClass().getName() + " lastUpdateString: " + lastUpdateString);
            ContentValues contentValues = new ContentValues();
            contentValues.put(DataBaseManager.ID_MEDICO, medico.getIdMedico());
            contentValues.put(DataBaseManager.ID_PERSONA, medico.getIdPersona());
            contentValues.put(DataBaseManager.ID_USUARIO, medico.getUsuario().getIdUsuario());
            contentValues.put(DataBaseManager.CEDULA, medico.getCedula());
            contentValues.put(DataBaseManager.ESPECIALIDAD, medico.getEspecialidad());
            try {
                sqLiteDatabase.insertOrThrow(DataBaseManager.HLC_MEDICO_TAB, null, contentValues);
            } catch (android.database.sqlite.SQLiteConstraintException exSQL) {
                sqLiteDatabase.update(DataBaseManager.HLC_MEDICO_TAB, contentValues,
                        DataBaseManager.ID_MEDICO + " = " + medico.getIdMedico(), null);
                Log.e(Constantes.LOG_ID, this.getClass().getName() + " Error Administrado");
            }
            contentValues = new ContentValues();
            contentValues.put(DataBaseManager.ID_PERSONA, medico.getIdPersona());
            contentValues.put(DataBaseManager.NOMBRE, medico.getNombre());
            contentValues.put(DataBaseManager.APELLIDO_PATERNO, medico.getApPaterno());
            contentValues.put(DataBaseManager.APELLIDO_MATERNO, medico.getApMaterno());
            contentValues.put(DataBaseManager.TELEFONO, medico.getTelefono());
            contentValues.put(DataBaseManager.CELULAR, medico.getCelular());
            contentValues.put(DataBaseManager.EMAIL, medico.getEmail());
            contentValues.put(DataBaseManager.GENERO, String.valueOf(medico.getGenero()));
            contentValues.put(DataBaseManager.COLONIA, medico.getColonia());
            contentValues.put(DataBaseManager.CIUDAD, medico.getCiudad());
            contentValues.put(DataBaseManager.ESTADO, medico.getEstado());
            contentValues.put(DataBaseManager.CP, medico.getCodigoPostal());
            try {
                sqLiteDatabase.insertOrThrow(DataBaseManager.HLC_PERSONA_TAB, null, contentValues);
            } catch (android.database.sqlite.SQLiteConstraintException exSQL) {
                sqLiteDatabase.update(DataBaseManager.HLC_PERSONA_TAB, contentValues,
                        DataBaseManager.ID_PERSONA + " = " + medico.getIdPersona(), null);
                Log.e(Constantes.LOG_ID, this.getClass().getName() + " Error Administrado");
            }

            contentValues = new ContentValues();
            contentValues.put(DataBaseManager.ID_USUARIO, medico.getUsuario().getIdUsuario());
            contentValues.put(DataBaseManager.ACTIVO, medico.getUsuario().getActivo());
            contentValues.put(DataBaseManager.NICK, medico.getUsuario().getNick());
            contentValues.put(DataBaseManager.PASSWORD, medico.getUsuario().getPass());
            contentValues.put(DataBaseManager.ULTIMA_CONEXION, ultimaConexion);
            contentValues.put(DataBaseManager.ULTIMA_ACTUALIZACION, lastUpdateString);
            contentValues.put(DataBaseManager.TIPO_USUARIO, medico.getUsuario().getTipoUsuario());
            try {
                sqLiteDatabase.insertOrThrow(DataBaseManager.HLC_USUARIO_TAB, null, contentValues);
            } catch (android.database.sqlite.SQLiteConstraintException exSQL) {
                sqLiteDatabase.update(DataBaseManager.HLC_USUARIO_TAB, contentValues,
                        DataBaseManager.ID_USUARIO + " = " + medico.getUsuario().getIdUsuario(), null);
                Log.e(Constantes.LOG_ID, this.getClass().getName() + " Error Administrado");
            }

            sqLiteDatabase.close();

        }

    }

    public void existMedicoByNickPass(String nick, String pass) {
        boolean existUser = false;
        Log.d("Logger MedicoDAO", "existMedicoByNickPass");
        DataBaseManager dataBaseManager = new DataBaseManager(this.context);
        SQLiteDatabase sqLiteDatabase = dataBaseManager.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT " + DataBaseManager.ID_MEDICO
                        + " FROM " + DataBaseManager.HLC_USUARIO_TAB + " us, " + DataBaseManager.HLC_MEDICO_TAB + " me"
                        + " WHERE "
                        + "us." + DataBaseManager.ID_USUARIO + " = me." + DataBaseManager.ID_USUARIO + " AND "
                        + DataBaseManager.NICK + " = ? AND  "
                        + DataBaseManager.PASSWORD + " = ? ",
                new String[]{nick, pass}
        );
        if (cursor != null) {
            if (cursor.getCount() == 1) {
                existUser = true;
            }
            if (cursor.moveToFirst()) {
                do {
                    String idMedico = String.valueOf(cursor.getInt(0));
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString(Constantes.ID_MEDICO_KEY, idMedico);
                    editor.commit();
                } while (cursor.moveToNext());
            } else {
                Log.d("Logger ESCOM: ", "Nulo DAO Medico");
            }
        }
        Message msgObj = handler.obtainMessage();
        Bundle bundleMessage = new Bundle();
        int codeResponse;
        if (existUser) {
            codeResponse = Constantes.EXITO;
        } else {
            codeResponse = 101;
        }
        bundleMessage.putInt("message", codeResponse);
        msgObj.setData(bundleMessage);
        handler.sendMessage(msgObj);
        sqLiteDatabase.close();
    }


    public String obetnerFechaUltimoUpdate(String idMedico) {
        Log.d("Logger MedicoDAO", "existMedicoByNickPass");
        String ultimaActualizacion = "";
        DataBaseManager dataBaseManager = new DataBaseManager(this.context);
        SQLiteDatabase sqLiteDatabase = dataBaseManager.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT ultima_actualizacion FROM "
                + "hlc_medico_tab me, hlc_usuario_tab us "
                + "WHERE me.id_usuario = us.id_usuario "
                + "AND me.id_medico = ?", new String[]{idMedico});
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                do {
                    ultimaActualizacion = String.valueOf(cursor.getString(0));
                } while (cursor.moveToNext());
            } else {
                Log.d("Logger ESCOM: ", "Nulo DAO Medico");
            }
        }
        return ultimaActualizacion;
    }

    public void insertarFechaUltimoUpdate(String idMedico) {
        DataBaseManager dataBaseManager = new DataBaseManager(this.context);
        SQLiteDatabase sqLiteDatabase = dataBaseManager.getWritableDatabase();
        if (sqLiteDatabase != null) {
            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constantes.FORMAT_DATE);
            String ultimaConexion = simpleDateFormat.format(calendar.getTime());
            try {
                sqLiteDatabase.execSQL("UPDATE hlc_usuario_tab SET " +
                        "ultima_actualizacion = '" + ultimaConexion + "'" +
                        " WHERE " +
                        "id_usuario = (SELECT id_usuario FROM hlc_medico_tab WHERE id_medico = " + idMedico + ")");
            } catch (android.database.sqlite.SQLiteConstraintException exSQL) {
                Log.e(Constantes.LOG_ID, this.getClass().getName() + " Error Administrado");
            }
            sqLiteDatabase.close();
        }
    }

    public List<MedicoVO> retrieveMedicos() {
        Log.d("Logger MedicoDAO", "retrieveMedicos");
        DataBaseManager dataBaseManager = new DataBaseManager(this.context);
        SQLiteDatabase sqLiteDatabase = dataBaseManager.getWritableDatabase();
        Cursor cursor = sqLiteDatabase.rawQuery("SELECT "
                + "me.id_medico,"
                + "pe.id_persona,"
                + "us.id_usuario,"
                + "me.cedula,"
                + "me.especialidad,"
                + "pe.nombre,"
                + "pe.apellido_paterno,"
                + "pe.apellido_materno,"
                + "pe.telefono,"
                + "pe.celular,"
                + "pe.email,"
                + "pe.genero,"
                + "pe.colonia,"
                + "pe.ciudad,"
                + "pe.estado,"
                + "pe.cp,"
                + "us.activo,"
                + "us.nick,"
                + "us.password,"
                + "us.ultima_conexion,"
                + "us.ultima_actualizacion,"
                + "us.tipo_usuario"
                + "FROM"
                + "hlc_medico_tab me, hlc_persona_tab pe, hlc_usuario_tab us"
                + "WHERE pe.id_persona=me.id_medico"
                + "WHERE us.id_usuario=me.id_usuario", null);

        List<MedicoVO> medicos = new ArrayList<MedicoVO>();
        if (cursor.moveToFirst()) {
            do {
                MedicoVO medico = new MedicoVO();
                medico.setIdMedico(String.valueOf(cursor.getInt(0)));
                medico.setIdPersona(String.valueOf(cursor.getInt(1)));
                UsuarioVO usuario = new UsuarioVO();
                usuario.setIdUsuario(String.valueOf(cursor.getInt(2)));
                medico.setUsuario(usuario);
                medico.setCedula(cursor.getString(3));
                medico.setEspecialidad(cursor.getString(4));
                medico.setNombre(cursor.getString(5));
                medico.setApPaterno(cursor.getString(6));
                medico.setApMaterno(cursor.getString(7));
                medico.setTelefono(cursor.getString(8));
                medico.setCelular(cursor.getString(9));
                medico.setEmail(cursor.getString(10));
                medico.setGenero(cursor.getString(11).charAt(0));
                medico.setColonia(cursor.getString(12));
                medico.setCiudad(cursor.getString(13));
                medico.setEstado(cursor.getString(14));
                medico.setCodigoPostal(cursor.getString(15));
                usuario.setActivo(cursor.getString(16));
                usuario.setNick(cursor.getString(17));
                usuario.setPass(cursor.getString(18));
                usuario.setUltimaConexion(cursor.getString(19));
                usuario.setUltimaActualizacion(cursor.getString(20));
                usuario.setTipoUsuario(cursor.getString(21));


            } while (cursor.moveToNext());
        } else {
            Log.d("Logger MedicoDAO", "NULO");
        }
        sqLiteDatabase.close();
        return medicos;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public void setSharedpreferences(SharedPreferences sharedpreferences) {
        this.sharedpreferences = sharedpreferences;
    }

}
